/*
Title:      	AltFontPrev
Author:     	Sam Rayner
More Info: 		http://samrayner.com/archives/altfontprev/
*/

function altFontPrev() {

  var afpVersion = '0.1';
  var releaseDate = '10th July 08';

  //array used to hold declared fonts
  var fontArray = [];
  
  //array used to hold CSS selectors
  var selArray = [];
  
  //see selArray for use
  var selNum = 0;

  //loop through linked and inline stylesheets
  for(var i = 0; i < document.styleSheets.length; i++) {
  	//loop through CSS rules in the current stylesheet
    for(var j = 0; j < document.styleSheets[i].cssRules.length; j++) {	
      
      //var to store comma separated list of fonts as declared with FONT or FONT-FAMILY
      var fontFam = document.styleSheets[i].cssRules[j].style.getPropertyValue('font-family');
      
      //if fonts are declared in the current CSS rule
      if(fontFam) {
        
        //store CSS selector in an array of selectors, numbered in the order it appears
        selArray[selNum] = document.styleSheets[i].cssRules[j].selectorText;
      
        //create an array of fonts from the comma separated list 
        var indFonts = fontFam.split(",");
        
        /*add a 2nd dimension to the font array so fonts can be referenced 
        by selector number then font number in order declared*/
        fontArray[selNum] = new Array(indFonts.length - 1);
          
          //loop through fonts in the array of fonts declared for the selector in question
          for(var fontNum = 0; fontNum < indFonts.length; fontNum++) {
          
            //trim any spaces or quotation marks from the start and end of the font names
          	indFonts[fontNum] = indFonts[fontNum].replace(/^\s+|'+|"+|\s+$|'+$|"+$/g,"");
          	
          	//store each font in the 2nd dimension of the font array
            fontArray[selNum][fontNum] = indFonts[fontNum].toLowerCase();
          }  
        
        //move on to the next CSS selector  
        selNum++;
        
      }
    }
  }
  
  //append a stylesheet link to the page's head to style the AFP panel
  var afpCSS = document.createElement('link');
  afpCSS.rel = 'stylesheet';
  afpCSS.type = 'text/css';
  afpCSS.href = '../afp.css';
  document.getElementsByTagName("head")[0].appendChild(afpCSS);
  
//IF FONTS FOUND
if(selArray.length != 0) {  
  
  //create a dropdown option for every selector in the selectors array
  var selOptions = '';
    
  for(i = 0; i < selArray.length; i++) {
    selOptions += '<option>' + selArray[i] + '</option>';
  }
  
  //create a dropdown option for every font for a particular selector in the fonts array
  function getFonts(selector) {
    var fontOptions = '';
    
    for(i = 0; i < fontArray[selector].length; i++) {
      fontOptions += '<li ';
      
      if(i == 0) {
        fontOptions += 'id="afp-current" ';
      }
      
      fontOptions += 'style="font-family: ' + fontArray[selector][i] + ', helvetica"><a ';
      
      if(i % 2 == 0) {
        fontOptions += 'class="afp-stripe" ';
      }
      
      fontOptions += 'href="#' + fontArray[selector][i].replace(/^[\s]/g,"%20") + '">'
      
      //add "default" label to any generic font declaration
      if(fontArray[selector][i] == "serif" 
         || fontArray[selector][i] == "sans-serif" 
         || fontArray[selector][i] == "cursive" 
         || fontArray[selector][i] == "fantasy" 
         || fontArray[selector][i] == "monospace") {
        fontOptions += 'default ';
      }
      
      fontOptions += fontArray[selector][i] + '<span style="font-family: ' + fontArray[selector][i] + ', wingdings">o</span></a></li>';
    }
    
    return fontOptions;
  }
  
  //prepare the HTML needed for the AFP panel with the appropriate dropdown options
  var afpHTML = '<div id="altfontprev" class="afp-show"><p id="afp-title"><span></span>AltFontPrev</p><form><label for="selector">Selector:</label><select name="selector" id="afp-selectors">' 
  + selOptions + 
  '</select></form><ul id="afp-fonts">' 
  + getFonts(0) + 
  '</ul><form><label for="afp-custom">Custom:</label><input disabled="true" id="afp-custom" type="search" value="Custom Font"></input></form><img id="close-icon" src="http://files.samrayner.com/scripts/altfontprev/images/close.png" width="13" height="13" alt="Close" title="Close" /><img id="info-icon" src="http://files.samrayner.com/scripts/altfontprev/images/info.png" width="13" height="13" alt="Info" title="Info" /><div id="afp-info" class="afp-hide"><span></span><p>v.' 
  + afpVersion + 
  '<em>('
  + releaseDate +
  ')</em></p><p>Created by <a href="http://samrayner.com/">Sam Rayner</a></p><p><a target="_blank" href="http://samrayner.com/archives/altfontprev/">More Info&hellip;</a></p></div></div>'
  
  //append the AFP HTML to the bottom of the page
  document.getElementsByTagName("body")[0].innerHTML += afpHTML;

  var selSelect = document.getElementById("afp-selectors");
  var fontList = document.getElementById("afp-fonts");
  
  //change options in fontSelect depending on selector chosen by passing option's index to getFonts
  function selChange() {
    fontList.innerHTML = getFonts(selSelect.selectedIndex);
    
  //fire fontChange when user selects a font
  	for(var i = 0; i < fontList.childNodes.length; i++) {
      fontList.childNodes[i].firstChild.addEventListener("click", fontChange, false);
    }
  }
  
}
//IF NO FONTS FOUND
else { 
  
    //alternatively give error message if no font-family declarations found
    var noFontsHTML = '<div id="altfontprev" class="afp-show"><p id="afp-title"><span></span>AltFontPrev</p><form><label for="selector">Selector:</label><select disabled="true" name="selector" id="afp-selectors"><option>None</option></select></form><ul id="afp-fonts"><li class="afp-error">No font lists found&hellip;</li></ul><form><label for="afp-custom">Custom:</label><input disabled="true" id="afp-custom" type="search" value="Not available"></input></form><img id="close-icon" src="http://files.samrayner.com/scripts/altfontprev/images/close.png" width="13" height="13" alt="Close" title="Close" /><img id="info-icon" src="http://files.samrayner.com/scripts/altfontprev/images/info.png" width="13" height="13" alt="Info" title="Info" /><div id="afp-info" class="afp-hide"><span></span><p>v.' 
    + afpVersion + 
    '<em>('
    + releaseDate +
    ')</em></p><p>Created by <a href="http://samrayner.com/">Sam Rayner</a></p><p><a target="_blank" href="http://samrayner.com/archives/altfontprev/">More Info&hellip;</a></p></div></div>'
  
    document.getElementsByTagName("body")[0].innerHTML += noFontsHTML;
}
  
  function fontChange() {
  
    var currentFont = document.getElementById('afp-current');
    
    currentFont.removeAttribute('id', 0);
    
    this.parentNode.setAttribute('id', 'afp-current');
  
    var selIndex = selSelect.selectedIndex;
	var liArray = this.parentNode.parentNode.childNodes;
	
	for(var i = 0; i < liArray.length; i++) {
	  if(liArray[i] == this.parentNode) {
	    var fontIndex = i;
	  }
	}
  
    //get the last stylesheet attached to the page
    var lastSheet = document.styleSheets[document.styleSheets.length - 1];
    
    //create a new font-family rule with chosen font at start...
    var newFonts = selArray[selIndex] + ' {font-family: ' + fontArray[selIndex][fontIndex];
    
    //... and rest of fonts to follow
    for(i = 0; i < fontArray[selIndex].length; i++) {
      newFonts += ', "' + fontArray[selIndex][i] + '"';
    }
    
    //close off the rule
    newFonts += ';} ';
    
    //append it to the bottom of the stylesheet
    lastSheet.insertRule(newFonts, lastSheet.cssRules.length);
  }
  
  //fire selChange when user changes selector
  selSelect.addEventListener("change", selChange, false);
  
  //fire fontChange when user selects a font
  for(var i = 0; i < fontList.childNodes.length; i++) {
    fontList.childNodes[i].firstChild.addEventListener("click", fontChange, false);
  }
  
  var closeIcon = document.getElementById("close-icon");
  var infoIcon = document.getElementById("info-icon");
  
  function closePane() {
    var afpPane = document.getElementById('altfontprev');
    afpPane.setAttribute('class', 'afp-hide');
  }
  
  function showInfo() {
    var afpInfo = document.getElementById('afp-info');
  
  	if(afpInfo.getAttribute('class') == 'afp-hide') {
      afpInfo.setAttribute('class', 'afp-show');
    }
    else {
      afpInfo.setAttribute('class', 'afp-hide');
    }
  }
  
  closeIcon.addEventListener("click", closePane, false);
  infoIcon.addEventListener("click", showInfo, false);
}